import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('MovingSceneBg')
export class MovingSceneBg extends Component {
    // 背景属性
    @property(Node)
    public bg01: Node = null
    @property(Node)
    public bg02: Node = null

    // 背景移动速度
    private _bgSpeed = 10
    // 背景移动范围
    private _bgMovingRange = 80
    // 是否移动
    private _isMove = true

    start() {
        this._init()
    }

    update(deltaTime: number) {
        // 参数deltaTime表示帧间隔时间
        if(!this._isMove) return
        this._moveBackground(deltaTime)
    }

    // 初始化
    private _init() {
        // 重置bg01和bg02位置
        this.bg01.setPosition(0, 0, 0)
        this.bg02.setPosition(0, 0, -this._bgMovingRange)
    }

    // 移动背景方法
    private _moveBackground(deltaTime: number) {
        this.bg01.setPosition(0, 0, this.bg01.position.z + this._bgSpeed * deltaTime)
        this.bg02.setPosition(0, 0, this.bg02.position.z + this._bgSpeed * deltaTime)

        if (this.bg01.position.z > this._bgMovingRange) {
            this.bg01.setPosition(0, 0, this.bg02.position.z - this._bgMovingRange)
        }
        if (this.bg02.position.z > this._bgMovingRange) {
            this.bg02.setPosition(0, 0, this.bg01.position.z - this._bgMovingRange)
        }
    }
}

